<template>
    <navigation></navigation>
    <div class="min-h-screen bg-gray-50 py-12">
        <!-- 主内容区域 -->
        <div class="max-w-7xl mx-auto px-4 mt-12">
            <!-- 标题区域 -->
            <div class="flex justify-between items-center mb-8">
                <h2 class="text-3xl font-bold">课程中心</h2>
                <div class="relative">
                    <input type="text" placeholder="搜索课程..." class="pl-10 pr-4 py-2 rounded-lg border focus:outline-none focus:ring-2 focus:ring-blue-500 w-64">
                    <i class="fa fa-search absolute left-3 top-3 text-gray-400"></i>
                </div>
            </div>
            
            <!-- 分类和内容区域 -->
            <div class="flex gap-6">
                <!-- 左侧课程分类 -->
                <div class="w-1/5">
                    <div class="bg-white rounded-lg shadow-lg p-4 sticky top-24">
                        <h3 class="text-xl font-semibold mb-4">课程分类</h3>
                        <ul class="space-y-2">
                            <li>
                                <button
                                    @click="selectedCategory = 'all'"
                                    :class="selectedCategory === 'all' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                    class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                                >
                                    <i class="fa fa-th-large mr-2"></i>全部课程
                                </button>
                            </li>
                            <li>
                                <button
                                    @click="selectedCategory = 'frontend'"
                                    :class="selectedCategory === 'frontend' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                    class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                                >
                                    <i class="fa fa-code mr-2"></i>前端开发
                                </button>
                            </li>
                            <li>
                                <button
                                    @click="selectedCategory = 'ai'"
                                    :class="selectedCategory === 'ai' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                    class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                                >
                                    <i class="fa fa-robot mr-2"></i>人工智能
                                </button>
                            </li>
                            <li>
                                <button
                                    @click="selectedCategory = 'database'"
                                    :class="selectedCategory === 'database' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                    class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                                >
                                    <i class="fa fa-database mr-2"></i>数据库
                                </button>
                            </li>
                            <li>
                                <button
                                    @click="selectedCategory = 'backend'"
                                    :class="selectedCategory === 'backend' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                    class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                                >
                                    <i class="fa fa-server mr-2"></i>后端开发
                                </button>
                            </li>
                            <li>
                                <button
                                    @click="selectedCategory = 'java'"
                                    :class="selectedCategory === 'java' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                    class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                                >
                                    <i class="fa fa-coffee mr-2"></i>Java开发
                                </button>
                            </li>
                          <li>
                            <button
                                @click="selectedCategory = 'programming'"
                                :class="selectedCategory === 'programming' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                            >
                              <i class="fa fa-terminal mr-2"></i>编程基础
                            </button>
                          </li>
                          <li>
                            <button
                                @click="selectedCategory = 'finance'"
                                :class="selectedCategory === 'finance' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                            >
                              <i class="fa fa-money mr-2"></i>金融
                            </button>
                          </li>
                          <li>
                            <button
                                @click="selectedCategory = 'other'"
                                :class="selectedCategory === 'other' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'"
                                class="w-full py-2 px-4 rounded-lg transition-all duration-300 hover:bg-blue-500 hover:text-white"
                            >
                              <i class="fa fa-ellipsis-h mr-2"></i>其他
                            </button>
                          </li>
                        </ul>

                        <!-- 热门标签 -->
                        <div class="mt-8">
                            <h3 class="text-xl font-semibold mb-4">热门标签</h3>
                            <div class="flex flex-wrap gap-2">
                                <span class="px-3 py-1 bg-gray-100 rounded-full text-sm hover:bg-blue-100 transition-colors cursor-pointer">#Python</span>
                                <span class="px-3 py-1 bg-gray-100 rounded-full text-sm hover:bg-blue-100 transition-colors cursor-pointer">#Vue.js</span>
                                <span class="px-3 py-1 bg-gray-100 rounded-full text-sm hover:bg-blue-100 transition-colors cursor-pointer">#React</span>
                                <span class="px-3 py-1 bg-gray-100 rounded-full text-sm hover:bg-blue-100 transition-colors cursor-pointer">#机器学习</span>
                                <span class="px-3 py-1 bg-gray-100 rounded-full text-sm hover:bg-blue-100 transition-colors cursor-pointer">#SpringBoot</span>
                                <span class="px-3 py-1 bg-gray-100 rounded-full text-sm hover:bg-blue-100 transition-colors cursor-pointer">#MySQL</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 右侧内容区域 -->
                <div class="w-4/5">
                    <!-- 推荐课程 -->
                    <div class="mb-12">
                        <h2 class="text-2xl font-bold mb-6">推荐课程</h2>
                        <swiper :modules="swiperModules" :slides-per-view="3" :space-between="30" :pagination="{ clickable: true }"
                            :autoplay="{ delay: 3000 }" class="mySwiper">
                            <swiper-slide v-for="course in filteredRecommendedCourses" :key="course.id">
                                <div class="bg-white rounded-lg shadow-lg overflow-hidden transition-all duration-300 hover:shadow-xl hover:-translate-y-1">
                                    <div class="h-48 w-full overflow-hidden">
                                        <img :src="course.image || 'https://picsum.photos/400/300'" :alt="course.title" class="w-full h-full object-cover transition-transform duration-500 hover:scale-110">
                                    </div>
                                    <div class="p-6">
                                        <div class="flex justify-between items-center mb-2">
                                            <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">{{ course.level }}</span>
                                            <span class="text-gray-500 text-sm"><i class="fa fa-users mr-1"></i>{{ course.students || 0 }}</span>
                                        </div>
                                        <h3 class="text-xl font-semibold mb-2">{{ course.title }}</h3>
                                        <p class="text-gray-600 mb-4 line-clamp-2">{{ course.description }}</p>
                                        <div class="flex justify-between items-center">
                                            <div class="flex items-center">
                                                <img :src="course.teacherAvatar || 'https://picsum.photos/32/32'" :alt="course.teacher" class="w-8 h-8 rounded-full mr-2">
                                                <span class="text-gray-600 text-sm">{{ course.teacher || '未知讲师' }}</span>
                                            </div>
                                            <span class="text-lg font-bold text-blue-600">¥{{ course.price || 0 }}</span>
                                        </div>
                                    </div>
                                </div>
                            </swiper-slide>
                        </swiper>
                    </div>
                    
                    <!-- 课程列表 -->
                    <div>
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-2xl font-bold">全部课程</h2>
                            <div class="flex items-center gap-4">
                                <span class="text-sm text-gray-500">共 {{ filteredCourses.length }} 门课程</span>
                                <div class="flex items-center">
                                    <label for="sort" class="text-sm text-gray-600 mr-2">排序:</label>
                                    <select id="sort" v-model="sortType" class="border rounded-lg px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                                        <option value="default">默认</option>
                                        <option value="priceAsc">价格从低到高</option>
                                        <option value="priceDesc">价格从高到低</option>
                                        <option value="students">人气优先</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            <div v-for="course in pagedCourses" :key="course.id" @click="jump(course.id)" class="bg-white rounded-lg shadow-lg overflow-hidden transition-all duration-300 hover:shadow-xl hover:-translate-y-1 cursor-pointer">
                                <div class="relative h-48 w-full overflow-hidden">
                                    <img :src="course.image || 'https://picsum.photos/400/300'" :alt="course.title" class="w-full h-full object-cover transition-transform duration-500 hover:scale-110">
                                    <div class="absolute top-3 left-3">
                                        <span class="px-2 py-1 bg-blue-500 text-white text-xs rounded-full">{{ course.category || '未知分类' }}</span>
                                    </div>
                                </div>
                                <div class="p-5">
                                    <h3 class="text-xl font-semibold mb-2 line-clamp-1">{{ course.title }}</h3>
                                    <p class="text-gray-600 mb-4 text-sm line-clamp-2">{{ course.description || '暂无描述' }}</p>
                                    <div class="flex justify-between items-center">
                                        <div class="flex items-center">
                                            <img :src="course.teacherAvatar || 'https://picsum.photos/32/32'" :alt="course.teacher" class="w-8 h-8 rounded-full mr-2">
                                            <span class="text-gray-600 text-sm">{{ course.teacher || '未知讲师' }}</span>
                                        </div>
                                        <span class="text-lg font-bold text-blue-600">¥{{ course.price || 0 }}</span>
                                    </div>
                                    <div class="mt-4 flex justify-between items-center text-sm text-gray-500">
                                        <span><i class="fa fa-clock-o mr-1"></i>{{ course.duration || '未知时长' }}</span>
                                        <span><i class="fa fa-users mr-1"></i>{{ course.students || 0 }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 分页 -->
                        <div class="flex justify-center mt-10">
                            <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize"
                                :page-sizes="[6, 9, 12, 15]" :total="filteredCourses.length"
                                layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                                @current-change="handleCurrentChange" class="!rounded-button" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, inject } from "vue";
import { Swiper, SwiperSlide } from 'swiper/vue';
import { useRouter } from "vue-router";
import { Pagination, Autoplay } from 'swiper/modules';
import { getAllcourse, getRecomment } from "../../api/student/course/course";
import navigation from '../../views/navigation.vue'

const router = useRouter()
const swiperModules = [Pagination, Autoplay];

// 课程分类状态
const selectedCategory = ref('all');
const sortType = ref('default');

// 课程数据
const courses = ref([])
const recommendedCourses = ref([])

// 分页相关
const currentPage = ref(1);
const pageSize = ref(6);

// 计算属性：根据分类筛选课程
const filteredCourses = computed(() => {
    let filtered = courses.value;
    
    // 按分类筛选
    if (selectedCategory.value !== 'all') {
        filtered = filtered.filter(course => {
          const categoryMap = {
            'frontend': '前端开发',
            'ai': '人工智能',
            'database': '数据库',
            'backend': '后端开发',
            'java': 'Java开发',
            // 新增的分类映射
            'programming': '编程基础',
            'finance': '金融',
            'other': '其他'
          };
            return course.category === categoryMap[selectedCategory.value];
        });
    }
    
    // 按排序方式排序
    switch (sortType.value) {
        case 'priceAsc':
            filtered = filtered.slice().sort((a, b) => a.price - b.price); break;
        case 'priceDesc':
            filtered = filtered.slice().sort((a, b) => b.price - a.price); break;
        case 'students':
            filtered = filtered.slice().sort((a, b) => b.students - a.students); break;
    }
    return filtered;
});

// 新增：分页后的课程
const pagedCourses = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredCourses.value.slice(start, end);
});

// 计算属性：根据分类筛选推荐课程
const filteredRecommendedCourses = computed(() => {
    if (selectedCategory.value === 'all') {
        return recommendedCourses.value;
    }

  const categoryMap = {
    'frontend': '前端开发',
    'ai': '人工智能',
    'database': '数据库',
    'backend': '后端开发',
    'java': 'Java开发',
    // 新增的分类映射
    'programming': '编程基础',
    'finance': '金融',
    'other': '其他'
  };
    
    return recommendedCourses.value.filter(course => 
        course.category === categoryMap[selectedCategory.value]
    );
});

onMounted(() => {
    fetchAllCourses()
    fetchRecommendedCourses()
});

function fetchAllCourses() {
    // 取一个很大的pagesize，确保拿到全部数据
    getAllcourse({ page: 1, pagesize: 1000 }).then(res => {
        // 兼容pb.items[0]为课程数组
        if (res && res.items && Array.isArray(res.items[0])) {
            courses.value = res.items[0]
        } else if (Array.isArray(res.data)) {
            courses.value = res.data
        } else {
            courses.value = []
        }
    })
}

function fetchRecommendedCourses() {
    // 推荐课程可用全部课程随机取3个
    getAllcourse({ page: 1, pagesize: 1000 }).then(res => {
        let all = []
        if (res && res.items && Array.isArray(res.items[0])) {
            all = res.items[0]
        } else if (Array.isArray(res.data)) {
            all = res.data
        }
        if (all.length > 3) {
            const indices = []
            while (indices.length < 3) {
                const idx = Math.floor(Math.random() * all.length)
                if (!indices.includes(idx)) indices.push(idx)
            }
            recommendedCourses.value = indices.map(i => all[i])
        } else {
            recommendedCourses.value = all
        }
    })
}

function jump(id) {
    router.push({
        path: '/courseMessage',
        query: {
            id: id
        }
    })
}

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
};
</script>

<style scoped>
.mySwiper {
    padding-bottom: 3rem;
}

/* 自定义分页样式 */
:deep(.el-pagination) {
    .el-pager li {
        border-radius: 4px;
        margin: 0 2px;
    }
    
    .btn-prev, .btn-next {
        border-radius: 4px;
    }
    
    .el-pager li.active {
        background-color: #3b82f6;
        color: white;
    }
}
</style>